package filter;

import com.wuda.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter("/user/*")
public class UserFilter implements Filter {


	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession(false); // 获取现有 session，如果没有则返回 null

		String requestURI = req.getRequestURI();
		boolean isLoggedIn = (session != null && session.getAttribute("user") != null);
		if (!isLoggedIn) {
			System.out.println("UserFilter-->用户未登录，请求的 URI: " + requestURI);
			// 如果用户未登录，重定向到登录页面
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}


		// 用户已登录且具有适当权限，继续处理请求
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}
}
